$(function(){
  creatStar("#star",50);
 
  localStorage.setItem("moneyCor", 0);
  localStorage.setItem("moneyErr", 0);
  getList();

  var time = 60;//答题时间

  $("#count-down").text(time);
  var count =  setInterval(function(){
    var lastTime = parseInt($("#count-down").text());
    if(lastTime === 0){
      $('body').append('<div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 4;"></div>');
      var cNum = parseInt(localStorage.getItem("moneyCor"));
      var eNum = parseInt(localStorage.getItem("moneyErr"));
      var cNum2 = parseInt(localStorage.getItem("moneyCor")) + parseInt(localStorage.getItem("moneyErr"));
      var tolNum = parseFloat(cNum/cNum2 + cNum).toFixed(2);
      var correctRate = parseInt(cNum/cNum2*10000);
      correctRate = correctRate/100;
      // alert("时间到共计答题"+cNum2+"正确答题"+cNum+"正确率"+parseFloat(cNum/cNum2).toFixed(4)*100+"%");




      moneyQustion.pop();//注意移除答题的最后一道题，没有结果
      //数组转字符串,判断题默认点击正确为0，点击错误为1，跳过为-1；
      var moneyQustionLast = moneyQustion.join(";");
      var moneyAnswerLast = moneyAnswer.join(";");
      if(cNum < 6){//过关题目数量
        window.Interface.challengeResults({
          results:"fail",
          starType:"finance", //游戏game,理财finance,生活life，健康healthy，育儿child,娱乐fun
          score:tolNum,//总分
          question:moneyQustionLast,//问题
          answer:moneyAnswerLast,//答案
          rightCnt:cNum,//正确答题数
          errorCnt:eNum//错误答题数
        },function(res){
          showResults("money","fail",0,0,0,0,false);
        });
      }else{
        window.Interface.challengeResults({
          results:"success",
          starType:"finance", //游戏game,理财finance,生活life，健康healthy，育儿child,娱乐fun
          score:tolNum,//总分
          question:moneyQustionLast,//问题
          answer:moneyAnswerLast,//答案
          rightCnt:cNum,//正确答题数
          errorCnt:eNum//错误答题数
        },function(res){
          showResults("money",res.type,cNum,correctRate+"%",tolNum,res.ranking,res.isSend);
        });
      }

      //正确答题，正确率，总分
      //moneyResults.postResults(cNum,CorrectRate+"%",tolNum);
      //板块，结果（擂主challenger，过关success,失败fail）,正确答题，正确率，总分,排名
      //showResults(moneyResults.start,moneyResults.type,cNum,CorrectRate+"%",tolNum,moneyResults.rank);

      clearInterval(count);
    }else{
      $("#count-down").text(lastTime-1);
    }

  },1000);

});

//定义全局变量，问题和答案
var moneyQustion =[];
var moneyAnswer =[];


//板块，结果（擂主challenger，过关success,失败fail）,正确答题，正确率，总分,排名
function showResults(start,type,cNum,rate,tolNum,rank,isSend){
  $.ajax({
    type: "GET",
    url: "pages/pop-"+type+".html",
    success: function(data){

      $("body").append(data);
      $(".pop-box").addClass("pop-"+start);
      $("#pop-cor").text(cNum);
      $("#pop-rate").text(rate);
      $("#pop-tol").text(tolNum);
      $("#pop-rank").text(rank);

      if(isSend){
        $(".pop-box .text").show();
      }else{
        $(".pop-box .text").hide();
      }

      $(".pop-box .close").on("click",function(){
        window.location.href='index.html';
      });

      $(".pop-box .btn-blue").on("click",function(){
        window.Interface.challengeNum({},function(res){
          if(res.finance<3){
            if(type==="fail"){
              window.location.href= start+'.html';//返回挑战页
              window.Interface.tracking('理财星球', '挑战结果页','不服再战');
            }else{
              window.location.href='index.html';//返回首页
              window.Interface.tracking('理财星球', '挑战结果页','挑战新高');
            }
          }else{
            showPop("每天最多挑战3次哟，去试试其他项目吧！","确定","index.html");
          }
        });
      });
      $(".pop-box .btn-green").on("click",function(){
        if(type==="fail"){
          window.location.href='index.html';//返回首页
        }else{
          window.Interface.shareUrl({
            starType:start
          },function(res){
            //window.location.href = res.url;
          });
          if(type==="success"){
            window.Interface.tracking('理财星球', '挑战结果页','分享战绩');
          }else{
            window.Interface.tracking('理财星球', '挑战结果页','分享擂主');
          }
        }
      });
      $(".pop-box a").on("click",function(){
        var rel = $(this).attr("rel");
        if(rel === "lottery.html"){
          window.Interface.tracking('理财星球', '挑战结果页','幸运抽奖');
        }
      });

    }
  });
}




function getList(){

  var arr = [];
  var $jsonData;
  $.ajax({
    type: "GET",
    url: "data/money.json",
    success: function(data){
      $jsonData = $(data.qustion);
      leg = $(data.qustion).length;
      for(var i = 1; i<=leg; i++){
        arr.push(i);
      };
      var nid1 = parseInt(randomInteger(1,leg));
      arr.remove(nid1);
      getQustion(nid1);
    }
  });







function getQustion(nid){

  $jsonData.each(function(n,v){
    if(v.id === nid){
      creatAnswer(v);
      return false;
    }
  })
}


function creatAnswer(data){
  moneyQustion.push(data.id);
  $("#answer-tit").text(data.tit);
  $(data.answerList).each(function(n,v){
    $("#col-"+(n+1)).text(v.answer);
    if(v.correct){
      judgeAnswer(n);
    }
  });
}

function judgeAnswer(id){
  var st,appendQustion = true;
  $("#option-list .col").off("click.answer").on("click.answer",function(){
    if($(this).index() === id){
      showTips("correct", "回答正确");
      $(this).addClass("correct");
      var cNum = parseInt(localStorage.getItem("moneyCor"))+1;
      localStorage.setItem("moneyCor", cNum);
      $("#result-correct span").text(cNum);
    }else{
      showTips("error","回答错误");
      $(this).addClass("error");
      $("#option-list .col:eq("+id+")").addClass("correct");

      var eNum = parseInt(localStorage.getItem("moneyErr"))+1;
      localStorage.setItem("moneyErr", eNum);
      $("#result-error span").text(eNum);
    }
    moneyAnswer.push($(this).text());
    appendQustion = false;
    st = setTimeout(function(){
      hideTips();
      var nid = getID();
      arr.remove(nid);
      getQustion(nid);
    },1000);
  });

  $(".btn-box .btn-next").off("click.nx").on("click.nx",function(){
    clearTimeout(st);
    if(appendQustion){
      moneyAnswer.push("-1");
    }
    hideTips();
    $("#option-list").removeClass("error");
    var nid = getID();
    arr.remove(nid);
    getQustion(nid);
  });

}

function getID(){
    var len = arr.length;
    if(len<=10){
      getList();
     // console.log("tikucuowu")
    }else{
      var i = Math.ceil(Math.random() * (len ))%len;
      return arr[i];
    }
}

function showTips(cn,text){
  $("#answer-tips").addClass(cn).fadeIn().find("span").text(text);
}
function hideTips(){
  $("#answer-tips").removeClass("correct error").hide();
  $("#option-list .col").removeClass("correct error")
}

}

